import axios from 'axios';
import { Message } from 'element-ui';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建axios实例
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.NODE_ENV === "production" ? "https://api.javaxmsz.com/" : '/api',
  // 超时
  timeout: 10000,
});

// 添加响应拦截器
request.interceptors.response.use(function (response) {
  if (response.data.success) {
    return response;
  } else if (response.data.code === 401) {
    window.location.href = window.location.origin + '/login';
  } else {
    Message.error(response.data.message || '服务异常！');
    return Promise.reject(response);
  }
}, function (error) {
  Message.error(error.message || '服务异常！');
  return Promise.reject(error);
});

export function setDefaultToken (token) {
  request.defaults.headers['LakerToken'] = token;
}

export const uploadUrl = process.env.NODE_ENV === "production" ? "http://120.26.240.98:8080/common/upload/file" : '/api/common/upload/file';

// 登录
export function login(userName, passWord) {
  return request({
    url: '/api/v1/login',
    method: 'post',
    data: {
      username: userName,
      password: passWord,
    },
  });
}

// 查询分类
export function getCategory() {
  return request({
    url: '/sh/category',
    method: 'get'
  });
}

// 查询分类下的标签
export function getLabels(category) {
  return request({
    url: '/sh/tag?page=1&limit=10000&category=' + category,
    method: 'get'
  });
}

export function addLabel(tagName, tagClassify) {
  return request({
    url: '/sh/tag',
    method: 'post',
    data: { tagName, tagClassify }
  });
}

export function deleteLabel(id) {
  return request({
    url: `/sh/tag/${id}`,
    method: 'delete'
  });
}

// 新增或更新博客
export function addBlog(data) {
  return request({
    url: '/sh/blog',
    method: 'post',
    data
  });
}

// 删除博客
export function deleteBlog(id) {
  return request({
    url: `/sh/blog/${id}`,
    method: 'delete'
  });
}

// 查询博客
export function queryBlog(params) {
  return request({
    url: '/sh/blog',
    method: 'get',
    params
  });
}

// 查询广告类型
export function getAdType() {
  return request({
    url: '/sh/category/advertisement',
    method: 'get'
  });
}

// 根据广告类型查询广告
export function getAdContent(type) {
  return request({
    url: `/sh/ad/type/${type}`,
    method: 'get'
  });
}

// 新建或更新广告
export function saveAd(data) {
  return request({
    url: '/sh/ad',
    method: 'post',
    data
  });
} 

